package lm.concurrency.day6.threadpool;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Auther: Min.Liu
 * @Description:
 * @Date: Created in 9:18 2024/11/8
 */
@Slf4j
class BlockingQueue<T> {
    // 1. 任务队列
    private Deque<T> queue = new ArrayDeque<>();

    // 2. 锁
    private ReentrantLock lock = new ReentrantLock();

    // 3. 生产者条件变量
    private Condition fullWaitSet = lock.newCondition();

    // 4. 消费者条件变量
    private Condition emptyWaitSet = lock.newCondition();

    // 5. 容量
    private int capcity;

    public BlockingQueue(int capcity) {
        this.capcity = capcity;
    }

    // 带超时阻塞获取
    public T poll(long timeout, TimeUnit unit) {
        lock.lock();
        try {
            // 将 timeout 统一转换为 纳秒
            long nanos = unit.toNanos(timeout);
            while (queue.isEmpty()) {
                try {
                    // 返回值是剩余时间
                    if (nanos <= 0) {
                        return null;
                    }
                    nanos = emptyWaitSet.awaitNanos(nanos);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            T t = queue.removeFirst();
            fullWaitSet.signal();
            return t;
        } finally {
            lock.unlock();
        }
    }

    // 阻塞获取
    public T take() {
        lock.lock();
        try {
            while (queue.isEmpty()) {
                try {
                    emptyWaitSet.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            T t = queue.removeFirst();
            fullWaitSet.signal();
            return t;
        } finally {
            lock.unlock();
        }
    }

    // 阻塞添加
    public void put(T task) {
        lock.lock();
        try {
            while (queue.size() == capcity) {
                try {
                    log.debug("等待加入任务队列 {} ...", task);
                    fullWaitSet.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            log.debug("加入任务队列 {}", task);
            queue.addLast(task);
            emptyWaitSet.signal();
        } finally {
            lock.unlock();
        }
    }

    // 带超时时间阻塞添加
    public boolean offer(T task, long timeout, TimeUnit timeUnit) {
        lock.lock();
        try {
            long nanos = timeUnit.toNanos(timeout);
            boolean wait = false;
            while (queue.size() == capcity) {
                wait = true;
                try {
                    if (nanos <= 0) {
                        log.debug("G,等待加入队列超时,任务队列 {} ...", task);
                        return false;
                    }
                    log.debug("等待加入任务队列 {} ...", task);
                    nanos = fullWaitSet.awaitNanos(nanos);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if (wait) {
                log.debug("等待后成功加入了任务队列 {}", task);
            } else {
                log.debug("无需等待，直接加入了任务队列 {}", task);
            }
            queue.addLast(task);
            emptyWaitSet.signal();
            return true;
        } finally {
            lock.unlock();
        }
    }

    public int size() {
        lock.lock();
        try {
            return queue.size();
        } finally {
            lock.unlock();
        }
    }

    public void tryPut(RejectPolicy<T> rejectPolicy, T task) {
        rejectPolicy.reject(this, task);
//        // 判断队列是否满
//        if (queue.size() == capcity) {
//            this.offer(task, 3000, TimeUnit.MILLISECONDS);
//            //rejectPolicy.reject(this, task);
//        } else {  // 有空闲
//            log.debug("直接加入任务队列 {}", task);
//            queue.addLast(task);
//            emptyWaitSet.signal();
//        }
    }


    public void tryPutNew(RejectPolicy<T> rejectPolicy, T task) {
        lock.lock();
        try {
            //1. 死等
            //this.put(task);
            //2) 带超时等待
            this.offer(task, 3000, TimeUnit.MILLISECONDS);
            //3) 让调用者放弃任务执行
            //log.debug("放弃{}", task);
            //4) 让调用者抛出异常
            //throw new RuntimeException("任务执行失败 " + task);
            //5) 让调用者自己执行任务
            //task.run();
        } finally {
            lock.unlock();
        }
    }

}
